# -*- coding: utf-8 -*-
'''
@author: wangwl
@file: docker
@time: 2021/07/5 17:30
@desc:
'''
import time
from components.deploy.soft_release.dao import deploy_event_in
from general.deploy.deploy_conf_create import DeployConfCreate
from utils.ssh_utils import SCPMet
from utils.views import ReturnClass
check_period = 5
check_count = 24


class DeployDocker():
    def __init__(self, soft_info, conf_list):
        self.soft_info = soft_info
        self.conf_list = conf_list
        self.docker_compose_data = ''

    def set_ssh(self):
        self.ssh = SCPMet()
        self.ssh.set_info(self.soft_info)
        self.ssh.connect()

    def ssh_close(self):
        self.ssh.close()

    def go_conf(self):
        DeployConfCreate.ssh_echo_input(self.ssh, self.soft_info['conf_manage_ids'], self.soft_info['deploy_event_ids'])
        # for conf_info_one in self.conf_list:
        #     conf_manage_path = os.path.split(conf_info_one['conf_manage_path'])
        #     cmd = "mkdir -p '{conf_manage_path_dir}' && echo '{conf_manage_content}' > {conf_manage_path}".format(
        #         conf_manage_path_dir=conf_manage_path[0],
        #         conf_manage_content=conf_info_one['conf_manage_content'],
        #         conf_manage_path=conf_info_one['conf_manage_path'])
        #     exe_info = self.ssh.execcmd(cmd)
        #
        #     if not ReturnClass.if_ok(exe_info):
        #         deploy_event_in(self.soft_info['deploy_event_ids'],
        #                         'DockerCompose文件[%s]生成失败(%s)' % (conf_info_one['conf_manage_path'], exe_info['data']), '0')
        #         return False
        #
        # deploy_event_in(self.soft_info['deploy_event_ids'],
        #                 'DockerCompose文件生成成功', '2')
        return True

    def judge_service_exist(self):
        """
        地容器镜像命名： linkapp_api-backend:3.2.0.auto.2021-07-06-10-13-52
        """
        shell_command = "docker inspect %s -f '{{.Name}}' >/dev/null 2>&1 && echo $?" %self.soft_info['soft_nick']

        command_result = self.ssh.execcmd(shell_command)

        if ReturnClass.if_ok(command_result):
            if not command_result['data'] or command_result['data'] != '0':
                return True

        deploy_event_in(self.soft_info['deploy_event_ids'],
                        '服务已经存在，预备执行销毁动作', '2')
        return False

    def container_stop(self):
        if self.soft_info['soft_stop_cmd']:
            shell_command = self.soft_info['soft_stop_cmd']
            deploy_event_in(self.soft_info['deploy_event_ids'],
                            '使用维护命令进行停止', '2')
        else:
            deploy_event_in(self.soft_info['deploy_event_ids'],
                            '未维护命令，使用服务名进行销毁', '2')

            shell_command = "docker stop %s" % self.soft_info['soft_nick']

        deploy_event_in(self.soft_info['deploy_event_ids'],
                        '停止命令已经发送，请稍后', '2')
        command_result = self.ssh.execcmd(shell_command)
        if ReturnClass.if_ok(command_result):
            deploy_event_in(self.soft_info['deploy_event_ids'],
                            '停止成功', '2')
            return True
        else:
            deploy_event_in(self.soft_info['deploy_event_ids'],
                            '停止失败', '0')
            return False

    def container_install(self):
        for conf_list_one in self.conf_list:
            if conf_list_one['conf_manage_code'] == 'dockercompose':
                self.docker_compose_data = conf_list_one

        if not self.docker_compose_data:
            deploy_event_in(self.soft_info['deploy_event_ids'],
                            'DockerCompose文件没有设置，无法进行容器部署', '0')
            return False

        #shell_command = "cd  %s; docker-compose up -d" %self.soft_info['soft_install_url']
        shell_command = "cd  %s && docker-compose -f %s up -d " % (self.soft_info['soft_install_url'],self.docker_compose_data['conf_manage_path'])

        command_result = self.ssh.execcmd(shell_command)

        deploy_event_in(self.soft_info['deploy_event_ids'],
                        'Docker Dep Result: %s' %command_result, '2')

        return True
        # if ReturnClass.if_ok(command_result):
        #     deploy_event_in(self.soft_info['deploy_event_ids'],
        #                     '执行创建构建成功', '1')
        #     return True
        # else:
        #     deploy_event_in(self.soft_info['deploy_event_ids'],
        #                     '执行创建构建失败(%s)'%command_result['data'], '0')
        #     return False

    def check_status(self):
        if self.soft_info['soft_check_code'] and self.soft_info['soft_check_url']:
            check_count_ = 1
            while check_count > check_count_:
                check_count_ += 1

                deploy_event_in(self.soft_info['deploy_event_ids'],
                                '心跳检查中，第【%s】次' % check_count_, '2')

                check_status_result = self.ssh.check_status(self.soft_info['soft_check_code'],
                                                            self.soft_info['soft_check_url'])

                if ReturnClass.if_ok(check_status_result):
                    deploy_event_in(self.soft_info['deploy_event_ids'],
                                    '部署成功', '1')
                    return True

                time.sleep(check_period)

            deploy_event_in(self.soft_info['deploy_event_ids'],
                            '在120秒内，心跳检查失败。请检查配置，或者登录服务器查询服务状态', '0')
            return False
        else:
            deploy_event_in(self.soft_info['deploy_event_ids'],
                            '未设置心跳方式或者信息，默认部署完成', '1')

    def deploy_end(self):
        self.ssh.close()


    def exec_install_docker(self):
        deploy_event_in(self.soft_info['deploy_event_ids'],
                        '开始处理,请稍后', '2')
        try:
            if not self.judge_service_exist():
                if not self.container_stop():
                    return False

            if not self.go_conf():
                return False

            if not self.container_install():
                return False

            self.check_status()

            self.deploy_end()
        except Exception as e:
            deploy_event_in(self.soft_info['deploy_event_ids'],
                            '部署失败(%s)' %e, '0')

        return True
